package com.ljl.yishu.ui;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.KeyEvent;
import android.widget.Toast;
import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.ActionBar.Tab;
import com.actionbarsherlock.app.SherlockFragment;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
import com.ljl.yishu.R;
import org.apache.log4j.Logger;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends SherlockFragmentActivity implements ActionBar.TabListener, OnPageChangeListener {

    /**
     * 顶部Tab的title
     */
    private String[] mTabTitles;

    /**
     * ViewPager对象的引用
     */
    private ViewPager mViewPager;

    /**
     * 装载Fragment的容器，我们的每一个界面都是一个Fragment
     */
    private List<Fragment> mFragmentList;

    /**
     * ActionBar对象的引用
     */
    private ActionBar mActionBar;
    private Fragment mFragment1;

    private static final Logger log = Logger.getLogger(MainActivity.class);

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        //从资源文件在获取Tab的title
        mTabTitles = getResources().getStringArray(R.array.tab_title_new);
        mFragmentList = new ArrayList<Fragment>();

        mViewPager = (ViewPager) findViewById(R.id.viewPager);
        //设置Adapter
        mViewPager.setAdapter(new TabPagerAdapter(getSupportFragmentManager(), mFragmentList));
        //设置监听
        mViewPager.setOnPageChangeListener(this);

        //获取Action实例我们使用getSupportActionBar()方法
        mActionBar = getSupportActionBar();
        mActionBar.setBackgroundDrawable((getResources().getDrawable(R.color.theme)));
        //隐藏Title
        mActionBar.setDisplayShowTitleEnabled(true);
        //隐藏Home logo
        mActionBar.setDisplayShowHomeEnabled(true);
        //设置ActionBar的导航模式为Tab
        mActionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

        //为ActionBar添加Tab并设置TabListener
        for (int i = 0; i < mTabTitles.length; i++) {
            ActionBar.Tab tab = mActionBar.newTab();
            tab.setText(mTabTitles[i]);

            tab.setTabListener(this);
            mActionBar.addTab(tab, i);
        }

        //将Fragment加入到List中，并将Tab的title传递给Fragment
//        for (int i = 0; i < mTabTitles.length; i++) {
//            Fragment fragment = new TuiJianFragment();
//            Bundle args = new Bundle();
//            args.putString("arg", mTabTitles[i]);
//            fragment.setArguments(args);
//
//            mFragmentList.add(fragment);
//        }

        Fragment tuiJianFragment = new TuiJianFragment();
        Bundle args0 = new Bundle();
        args0.putString("arg", mTabTitles[0]);
        tuiJianFragment.setArguments(args0);
        Fragment chengJiaoFragment = new ChengJiaoFragment();
        Bundle args1 = new Bundle();
        args1.putString("arg", mTabTitles[1]);
        chengJiaoFragment.setArguments(args1);
        Fragment fragment = new TuiJianFragment();
        Bundle args2 = new Bundle();
        args2.putString("arg", mTabTitles[2]);
        fragment.setArguments(args2);

        mFragmentList.add(tuiJianFragment);
        mFragmentList.add(chengJiaoFragment);
        mFragmentList.add(fragment);

        // Make sure the two menu fragments are created.
        FragmentManager fm = getSupportFragmentManager();
        FragmentTransaction ft = fm.beginTransaction();
        mFragment1 = fm.findFragmentByTag("f1");
        if (mFragment1 == null) {
            mFragment1 = new MenuFragment();
            ft.add(mFragment1, "f1");
        }
        ft.commit();
    }


    @Override
    public void onTabSelected(Tab tab, FragmentTransaction ft) {
        //点击ActionBar Tab的时候切换不同的Fragment界面
        mViewPager.setCurrentItem(tab.getPosition());
//       TextView view = (TextView) tab.getCustomView();
//       view.setTextSize(25);
    }

    @Override
    public void onTabUnselected(Tab tab, FragmentTransaction ft) {

    }

    @Override
    public void onTabReselected(Tab tab, FragmentTransaction ft) {

    }


    @Override
    public void onPageScrollStateChanged(int arg0) {

    }

    @Override
    public void onPageScrolled(int arg0, float arg1, int arg2) {

    }

    @Override
    public void onPageSelected(int arg0) {
        //滑动ViewPager的时候设置相对应的ActionBar Tab被选中
        mActionBar.setSelectedNavigationItem(arg0);

    }

    Exit exit = new Exit();

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            pressAgainExit();
        }
        return false;
    }


    /**
     * 再按一次退出程序。
     */
    private void pressAgainExit() {
        if (exit.isExit()) {
            finish();
        } else {
            Toast.makeText(getApplicationContext(), "再按一次退出程序",
                    1000).show();
            exit.doExitInOneSecond();
        }
    }

    class Exit {
        private boolean isExit = false;
        private Runnable task = new Runnable() {
            @Override
            public void run() {
                isExit = false;
            }
        };

        public void doExitInOneSecond() {
            isExit = true;
            HandlerThread thread = new HandlerThread("doTask");
            thread.start();
            new Handler(thread.getLooper()).postDelayed(task, 1000);
        }

        public boolean isExit() {
            return isExit;
        }

        public void setExit(boolean isExit) {
            this.isExit = isExit;
        }
    }

    /**
     * A fragment that displays a menu.  This fragment happens to not
     * have a UI (it does not implement onCreateView), but it could also
     * have one if it wanted.
     */
    public static class MenuFragment extends SherlockFragment {

        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setHasOptionsMenu(true);
        }

        @Override
        public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
            menu.add("登录").setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);


        }

        @Override
        public boolean onOptionsItemSelected(MenuItem item) {
            if (item.getTitle().equals("登录")) {
                Intent intent = new Intent(this.getActivity(), LoginIndex.class);
                startActivity(intent);
                getActivity().overridePendingTransition(R.anim.new_dync_in_from_right,R.anim.new_dync_out_to_left);
            }
            return super.onOptionsItemSelected(item);
        }
    }

}
